package com.mashibing.juc.c_008.interview;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName T05_WithoutVolatile_CountDownLatch
 * @Description 案例五，使用CountDownLatch来解决
 * @Author xiongwei.wu
 * @Date 2021/7/13 9:36
 **/
public class T05_WithoutVolatile_CountDownLatch {
    volatile List<Object> lists = new LinkedList();

    private void add(Object object) {
        lists.add(object);
    }

    private int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        T05_WithoutVolatile_CountDownLatch t = new T05_WithoutVolatile_CountDownLatch();

        CountDownLatch latch = new CountDownLatch(1);

        new Thread(() -> {
            System.out.println("T2启动");
            if (t.size() != 5) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("T2结束");
        }, "T2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("T1启动");
            for (int i = 0; i < 10; i++) {
                t.add(new Object());
                System.out.println("add: " + i);
                if (i == 5) {
                    latch.countDown();
                }
//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
            System.out.println("T1结束");
        }, "T1").start();
    }
}
